<template>
	<view>
		<view class="login">
			<view class="header">
				<view class="logo">
					<image src="/static/images/logo.png" style="width: 240rpx;height: 240rpx;" mode="widthFix"></image>
				</view>
			</view>
			<view class="tabs">
				<view class="tabs-item">
					<u-subsection :list="list" mode="button" @change="tabchange"></u-subsection>
				</view>
			</view>
			<view class="middle">
				<u-form :model="form" ref="uForm" :errorType="errorType">
					<u-form-item prop="account" class="inputarea" :border-bottom="false">
						<u-input v-model="form.account" type="number" border="border" class="input"
							:customStyle="{'padding-left':'2em','padding-top': '6rpx','padding-bottom': '6rpx'}"
							:placeholder="togglelogin?'请输入手机号':'请输入手机号'" />
						<u-icon name="account-fill" size="40" class="icon"></u-icon>
					</u-form-item>

					<!-- 短信登录 -->
					<template v-if="togglelogin">
						<u-form-item prop="mobilecaptcha" class="inputarea" :border-bottom="false">
							<view class="u-flex">
								<view class="u-flex-1">
									<u-input v-model="form.mobilecaptcha" type="number" class="input"
										:customStyle="{'padding-left':'2em','padding-top': '6rpx','padding-bottom': '6rpx'}"
										placeholder="输入短信验证码" borderColo />
									<u-icon name="email-fill" size="40" class="icon"></u-icon>
								</view>
								<view class="wrap">
									<u-toast ref="uToast"></u-toast>
									<u-verification-code :seconds="seconds" ref="uCode" @change="codeChange">
									</u-verification-code>
									<u-button size="mini" @click="getTelCode"
										:customStyle="{'border': '0px','font-size': '24rpx','height': '80rpx'}"
										:hairLine="false">{{tips}}</u-button>
								</view>
							</view>
						</u-form-item>
						<!-- <view @click="logisEnterprise">
							<u-checkbox v-model="isEnterprise">注册为客户组账号</u-checkbox>
						</view> -->
						<!-- <u-form-item class="inputarea" :border-bottom="false" v-if="isEnterprise">
							<u-input v-model="form.enterprisename" type="text" border="border" class="input"
								:customStyle="{'padding-left':'2em','padding-top': '6rpx','padding-bottom': '6rpx'}"
								placeholder="请输入客户组名称" />
							<u-icon name="home-fill" size="40" class="icon"></u-icon>
						</u-form-item>
						<u-form-item class="inputarea" :border-bottom="false" v-if="isEnterprise">
							<u-input v-model="form.cityName" type="select" border="border" class="input" @click="cityshow = true"
								:customStyle="{'padding-left':'2em','padding-top': '6rpx','padding-bottom': '6rpx'}"
								placeholder="请选择客户组地区" />
							<u-icon name="map-fill" size="40" class="icon"></u-icon>
						</u-form-item> -->
					</template>
					<!-- 账号密码登录 -->
					<template v-else>
						<u-form-item prop="password" class="inputarea" :border-bottom="false">
							<u-input v-model="form.password" type="password" border="border"
								:customStyle="{'padding-left':'2em','padding-top': '6rpx','padding-bottom': '6rpx'}"
								class="input" placeholder="输入密码" borderColo />
							<u-icon name="lock-fill" size="40" class="icon"></u-icon>
						</u-form-item>
					</template>
				</u-form>
				<view class="searchpassword" v-if="!togglelogin">
					<view class="searchpassword-item">
						<view class="forgetword">
							<navigator url="/pages/login/forgetpassword" class="u-font-28">忘记密码</navigator>
						</view>
					</view>
				</view>
				<!-- <view class="u-text-center u-p-t-30" v-if="togglelogin"><text class="u-tips-color">未注册手机号验证后自动创建青猿回收账户</text></view> -->
				<view class="botton">
					<view>
						<u-button @click="otherLogin" type="primary">{{togglelogin?'注册/登录':'登录'}}</u-button>
						<!-- <u-button open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber" type="primary">{{togglelogin?'注册/登录':'登录'}}</u-button> -->
					</view>
					<!-- #ifdef MP-WEIXIN -->
					<view class="u-m-t-30">
						<u-button class="btn" type="success" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
							<text class="u-p-l-10">手机号一键登录</text>
						</u-button>
					</view>
					<!-- #endif -->
					<view class="u-m-t-30">
						<u-button @click="gohome">不登录访问</u-button>
					</view>
				</view>
			</view>
			<view class="footer">
				<!-- #ifndef H5 -->
				<!-- <view class="u-p-b-20 text-title">
					<text>——</text><text class="u-p-l-10 u-p-r-10">快捷登录方式</text><text>——</text>
				</view>

				<button v-if="!isEnterprise" class="u-reset-button" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber">
					<text class="iconfont icon-yijiandenglu ico u-font-80"></text>
					<view class="u-p-t-8">
						<text class="u-font-24">一键登录</text>
					</view>
				</button> -->
				<!-- #endif -->

				<view class="tips">
					<view class="tipser">
						<u-checkbox v-model="agree" size="24"><text class="u-font-24 u-tips-color">我已知悉并同意</text></u-checkbox>
						<view class="text">
							<navigator url="/pages/home/regAgreement/regAgreement">《服务协议》</navigator>
						</view>及<view class="text">
							<navigator url="/pages/home/privacyPolicy/privacyPolicy">《隐私政策》</navigator>
						</view>
					</view>
				</view>
				<!-- <view class="text u-tips-color u-font-24 u-p-t-10">{{webSetting.copyright}}</view> -->
			</view>
		</view>
		<slider-verify :isShow="sliderVerifyFLag" @touchSliderResult="verifyResult" @refresh="refresh" @close="close"
			:pintuImg="pintuImg" :pintukuai="pintukuai" :ynumber="ynumber" ref="verifyElement"></slider-verify>
		<!-- <login-wechat :isWechat="isWechat"></login-wechat> -->
		
		<!-- 选择所在地区 -->
		<citypicker ref="citypicker" :show="cityshow" @select="getSelectCity" @close="cityshow = false"></citypicker>
		
		<!-- 阅读并同意青猿回收 -->
		<u-modal v-model="show" :show-cancel-button="true" title="温馨提示" confirm-text="同意" :confirm-style="{'color': '#10beca'}" cancel-text="不同意" width="600" @cancel="show = false" @confirm="agreeConfirm">
			<view class="tips u-p-l-20 u-p-r-20 u-m-t-30 u-m-b-30">
				<text class="u-font-24 u-tips-color">阅读并同意青猿回收</text>
				<view class="text">
					<navigator class="u-font-24" url="/pages/home/regAgreement/regAgreement">《服务协议》</navigator>
				</view>
				<text class="u-font-24">及</text>
				<view class="text">
					<navigator class="u-font-24" url="/pages/home/privacyPolicy/privacyPolicy">《隐私政策》</navigator>
				</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';

	export default {
		data() {
			return {
				list: [{
					name: '短信登录'
				}, {
					name: '密码登录'
				}, ],
				current: 1,
				countCodeImg: '', //验证码图片,
				// 这个是控制校验的
				issubmit: false,
				// 登录模式切换
				togglelogin: true,
				codeImg: '',
				tips: '',
				seconds: 60,
				errorType: ['toast'],
				form: {
					account: '',
					password: '',
					captcha: '',
					CaptchaGuid: '',
					mobilecaptcha: '',
					enterprisename: '',
					promotioncode: null,
					cityName: '',
					cityPath: ''
				},
				rules: {
					account: [{
							required: true,
							message: '请输入手机号',
							trigger: ['blur'],
						},
						// {
						// 	validator: (rule, value, callback) => {
						// 		// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
						// 		return this.$u.test.mobile(value);
						// 	},
						// 	message: '手机号码不正确',
						// 	// 触发器可以同时用blur和change，二者之间用英文逗号隔开
						// 	trigger: ['blur'],
						// }
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: ['blur'],
						},
						// {
						// 	// 正则不能含有两边的引号
						// 	pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$/,
						// 	message: '需同时含有字母和数字，长度在6-12之间',
						// 	trigger: ['change','blur'],
						// }
					],
					mobilecaptcha: [{
							required: true,
							message: '请输入验证码',
							trigger: ['change', 'blur'],
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur'],
						}
					],
					captcha: [{
							required: true,
							message: '请输入验证码',
							trigger: ['change', 'blur'],
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur'],
						}
					]
				},
				// 这个一开始是密码登录，要传一个上去
				apiLink: '/user/account/SMSLogin',
				key: '',
				showCode: false,
				// 滑块验证参数
				sliderVerifyFLag: false,
				pintuImg: '',
				pintukuai: '',
				ynumber: 0,
				// 登录方式显示
				isWechat: true,
				// 是否注册为客户组
				isEnterprise: false,
				agree: false,
				// 选择地区
				cityshow: false,
				// 用户协议
				show: false,
				loginType: 1, //1:一键登录，2:输入手机号码登录/注册
				phonecode: ''
			}
		},
		watch: {
			'form.mobilecaptcha'() {
				if (this.form.mobilecaptcha.length != 0 && this.form.account.length != 0) {
					this.issubmit = true
				} else {
					this.issubmit = false
				}
			},
			'form.account'() {
				if ((this.form.mobilecaptcha.length != 0 && this.form.account.length != 0) || (this.form.password.length !=
						0 && this.form.account.length != 0)) {
					this.issubmit = true
				} else {
					this.issubmit = false
				}
			},
			'form.password'() {
				if (this.form.account.length != 0 && this.form.password.length != 0) {
					this.issubmit = true
				} else {
					this.issubmit = false
				}
			}
		},
		computed: {
			...mapState({
				websetting: state => state.webSetting
			})
		},
		// onReady() {
		// 	this.$refs.uForm.setRules(this.rules);
		// },
		onLoad(opt) {
			uni.removeStorageSync('lifeData');
			

			this.key = opt.key;
			if (opt.status == 2) {
				uni.showToast({
					title: '登录异常或过期，请重新登录',
					duration: 3000,
					icon: 'none'
				})
			}
			
			// 推广邀请传参
			if(opt.promotioncode){
				console.log('promotioncode:',opt.promotioncode)
				this.form.promotioncode = opt.promotioncode
			}
		},
		methods: {
			logisEnterprise(){
				// console.log("触发客户组登录")
				
			},
			onGetPhoneNumber(e) {
				
				if (e.detail.errMsg == 'getPhoneNumber:ok') {
					this.phonecode = e.detail.code
					if(this.agree == false){
						this.show = true
						this.loginType = 1
						return
					}else{
						this.weixinLogin()
					}
				} else {
					console.log('您拒绝获取手机号码')
				}
			},
			weixinLogin(){
				uni.login({
					provider: 'weixin', //使用微信登录
					success: (res) => {
						if (res.code) {
							this.$u.get('/User/Account/WXLoginOrReg', {
								code: res.code,
								phonecode: this.phonecode
							}).then((res) => {
								uni.removeStorageSync('lifeData');
								this.$u.vuex('Authorization', res.token)
								this.$u.vuex('userdetail', {
									userid: res.userid
								})
								this.$store.dispatch('getDetails').then((res)=>{
									console.log('微信登录后获取用户详情：',res)
									uni.showToast({
										title: '登录成功'
									})
									uni.switchTab({
										url: '/pages/index/index'
									})
								}).catch((err)=>{
									console.log('err',err)
								})
							// 	console.log(res)
							// 	if (res.login == 0) { //已有账号时直接登录
							// 		console.log('Authorization', res.token.token)
							// 		this.$u.vuex('Authorization', res.token.token)
							// 		this.$u.vuex('exp', res.token.exp)
							// 		this.$u.vuex('userdetail', {
							// 			userid: res.token.userid
							// 		})
									
							// 		uni.showToast({
							// 			title: '登录成功'
							// 		})
									
							// 		uni.switchTab({
							// 			url: '/pages/index/index'
							// 		})
							// 	} else if (res.login == 1) { //否则注册
							// 		this.$u.post('/User/Account/Register', {
							// 			name: '手机尾号'+res.mobile.slice(-4),
							// 			mobile:res.mobile,
							// 			defaultPassType: 2, //0.888888 1.随机 2.手机后几位 -1为Password必填
							// 			isWxReg: true //false为个人注册 true为客户组注册
							// 		}).then(res => {
							// 			console.log(res)
							// 			uni.showToast({
							// 				title: '注册成功'
							// 			})
										
							// 			this.weixinLogin()
							// 		}).catch((error) => {
										
							// 		})
							// 	} else { //询问是否绑定微信
							// 		uni.showModal({
							// 			content: '您的手机号码已经绑定其他微信号，是否改为绑定现在的微信号?',
							// 			success: (mod) => {
							// 				if (mod.confirm) {
							// 					this.$u.get('/User/Account/ComfirmBindingWeiXing?mobile=' +res.mobile).then((res) => {
							// 						this.$u.vuex('Authorization',res.token.token)
							// 						this.$u.vuex('exp', res.token.exp)
							// 						this.$u.vuex('userdetail', {
							// 							enterpriseid: res.token.enterpriseid,
							// 							userid: res.token.userid
							// 						})
													
							
							// 						this.close()
							// 					})
							// 				} else if (mod.cancel) {
							// 					console.log('用户点击取消');
							// 				}
							// 			}
							// 		})
							// 	}
							})
						} else {
							console.log('登录失败！' + res.errMsg)
							uni.showToast({
								title: '登录失败',
								icon: 'none'
							})
						}
					}
				})
			},
			// 更新注册位置
			updateLat(){
				// 更新位置
				// uni.getLocation({
				// 	type: 'gcj02',
				// 	success: (res)=> {
				// 		console.log('当前位置的经度：' + res.longitude);
				// 		console.log('当前位置的纬度：' + res.latitude);
				// 		this.$u.post('/User/UpdateLat',{
				// 			lng: res.longitude,
				// 			lat: res.latitude
				// 		})
				// 	}
				// });
			},
			tabchange(v) {
				console.log(v)
				// 0为短信登录，1为密码登录
				if (v == 0) {
					this.togglelogin = true;
					this.apiLink = '/user/account/SMSLogin'
					
					// console.log('短信')
				} else {
					this.togglelogin = false;
					this.apiLink = '/user/account/login'
					
					// console.log('密码')
				}
				// this.$refs.uForm.resetFields()
			},
			// 获取滑块验证信息
			getSlideCaptch() {
				this.$u.get('/SlideCaptcha/GetSlideCaptcha').then((res) => {
					this.pintuImg = res.src1
					this.pintukuai = res.src2
					this.ynumber = res.ynumber
					this.form.guid = res.guidid
					this.sliderVerifyFLag = true
				})
			},
			// 滑块验证结果回调函数
			verifyResult(oldx) {
				this.form.captcha = Math.round(oldx);
				//togglelogin参数true为短信登录滑块验证回调，false为密码登录滑块验证回调
				if (this.togglelogin) {
					this.decideCode()
				} else {
					let form = {
						mobile: this.form.account,
						password: this.form.password,
						countresult: this.form.captcha,
						guid: this.form.guid
					}
					this.loginApi(form)
				}
			},
			// 关闭滑块验证弹窗
			close(state) {
				this.sliderVerifyFLag = state
			},
			// 刷新滑块验证
			refresh(state) {
				if (state) {
					this.getSlideCaptch();
				}
			},
			agreeConfirm(){
				this.agree = true
				if(this.loginType == 1){
					this.weixinLogin()
				}else if(this.loginType == 2){
					this.submit()
				}
			},
			// 验证码确定
			decideCode() {
				if (this.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在验证'
					})
					this.$u.get('/User/Account/SendLoginCaptcha?mobile=' + this.form.account + '&guid=' + this.form.guid + '&countresult=' + this.form.captcha).then((res) => {
						if (res) {
							this.sliderVerifyFLag = false;
							this.form.captcha = ""
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							this.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
							
						} else {
							this.getSlideCaptch();
						}
					}).catch((res) => {
						if (res.data.msg.err) {
							this.sliderVerifyFLag = false;
							return
						}
						this.$refs.verifyElement.refreshVerify();
						this.form.captcha = "";
					})
				}
			},
			otherLogin(){
				if(this.agree == false){
					this.show = true
					this.loginType = 2
					return
				}else{
					this.submit()
				}
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.removeStorageSync('lifeData');

						this.submitdata()
					} else {
						return false;
					}
				});
			},
			// 提交数据
			submitdata() {
				//togglelogin参数true为短信登录，false为密码登录
				let form = {}
				if (this.togglelogin) {
					let form = {
						mobile: this.form.account,
						captcha: this.form.mobilecaptcha,
						// regent:this.isEnterprise,
						// enterprisename:this.form.enterprisename,
						name: '手机尾号'+this.form.account.slice(-4),
						promotioncode: this.form.promotioncode,
						// cityPath: this.form.cityPath,
						// cityName: this.form.cityName,
					}
					this.loginApi(form)
					
				} else {
					// 密码登录前先弹出滑动验证
					this.getSlideCaptch();
					console.log("密码")
					
				}
			},
			// 登录接口
			loginApi(form) {
				console.log('loginApi:',form)
				this.agree = true
				this.$u.post(this.apiLink, form).then(res => {
					console.log('token',res)
					this.$u.vuex('Authorization', res.token)
					this.$u.vuex('userdetail', {
						userid: res.userid
					})
					
					this.$store.dispatch('getDetails').then((res)=>{
						console.log('微信登录后获取用户详情：',res)
						uni.showToast({
							title: '登录成功'
						})
					}).catch((err)=>{
						console.log('err',err)
					})
					
					this.updateLat()
					
					uni.showModal({
						content: '是否需要绑定微信以便使用一键登录？',
						success: (res)=> {
							if (res.confirm) {
								// #ifdef MP-WEIXIN
								uni.login({
									provider: 'weixin', //使用微信登录
									success: ret => {
										var code = ret.code
										this.$u.get('/User/Account/BindingWeiXin?code=' + code).then(data => {
											if (data.status == 0) {
												console.log(data.msg)
												uni.showToast({
													title: data.msg
												})
											}
										})
										uni.switchTab({
											url: '/pages/index/index'
										})
									}
								})
								// #endif
							}else if (res.cancel) {
								uni.switchTab({
									url: '/pages/index/index'
								})
							}
						}
					})
				}).catch((error) => {
					this.close(false)
					// if (error.data.msg == "账户名或密码错误") {
					// 	this.sliderVerifyFLag = false;
					// 	return
					// } else {
					// 	this.$refs.verifyElement.refreshVerify();
					// }
				})
			},
			// 点击获取验证码
			getTelCode() {
				if (this.form.account == '') {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					})
					return
				}
				if (this.$refs.uCode.canGetCode) {
					this.getSlideCaptch()
				}
			},

			codeChange(text) {
				this.tips = text;
			},
			gohome() {
				
				uni.switchTab({
					url: '/pages/index/index'
				})
			},
			getSelectCity(arr) { //城市选择回调函数
				console.log(arr)
				this.cityshow = false
				// this.selectArea = '';
				let cityidArr = [];
				let getArr = arr.filter(n => n.id != 0)
				let areaname = '';
				getArr.forEach((item, index) => {
					if (index == getArr.length - 1) {
						areaname += item.name
					} else {
						areaname += item.name + '-'
					}
					cityidArr.push(item.id);
				});
				if (cityidArr.length > 0)
					// this.form.cityPath = cityidArr[cityidArr.length - 1];
					this.form.cityPath = cityidArr.join(',');
				if (areaname)
					// this.form.cityName = areaname;
					this.form.cityName = areaname.split("-")[areaname.split("-").length - 1]
			},
		}
	}
</script>
<style lang="scss" scoped>
	.header {
		margin-top: 44px;
		padding-top: var(--status-bar-height);

		.logo {
			width: 240rpx;
			height: 268rpx;
			margin: 0 auto;
			text-align: center;
			color: $u-type-error;

			// background-image: url("@/static/images/logo.png");
			// background-position: center;
			// background-size: cover;
			.iconfont {
				font-size: 100rpx;
			}
		}

		.title {
			font-size: 50rpx;
			text-align: center;
			margin-top: 20rpx;
		}

		.title1 {
			font-size: 35rpx;
			margin-top: 20rpx;
			text-align: center;
		}
	}

	.footer {
		text-align: center;
		color: $u-color-grey;
		padding-bottom: 60rpx;
		padding-top: 30rpx;

		.ico {
			color: $u-type-primary;
		}

		.tips {
			display: flex;
			font-size: 24rpx;
			justify-content: center;
			align-items: baseline;
			margin-top: 40rpx;

			.tipser {
				display: flex;
				align-items: center;
				.text {
					color: $u-color-blue;
					display: inline-block;
				}
			}
		}
	}

	.login {
		min-height: 100vh;
		width: 100vw;
		background-color: white;
		padding: 40rpx 80rpx;
		border: 1px solid white;
		display: flex;
		flex-direction: column;

		.tabs {
			margin: 50rpx 0rpx 30rpx 0rpx;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			.tabs-item {
				width: 400rpx;
				border: 1px solid #f4f4f5;
				border-radius: 40rpx;
			}
		}

		.middle {
			flex: 1;

			.inputarea {
				position: relative;

				.input {
					// text-indent: 2em;
					// padding-left: 3em!important;
				}

				.icon {
					position: absolute;

					top: 44rpx;
					left: 20rpx;
					color: $u-color-grey;
				}

				.codeImg {
					// position: absolute;
					width: 120rpx;
					height: 50rpx;
					// top: 30rpx;
					// right: 10rpx;
				}

				.wrap {
					// position: absolute;
					// top: 20rpx;
					// left: 420rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					padding: 0;
					border: 0;
					background: inherit;
					z-index: 99;
					border-left: 1px solid $u-color-light;
				}

				.u-flex {
					border: 1px solid #dcdfe6;
					width: 100%;
					border-radius: 8rpx;
					padding: 0 0 0 20rpx;
				}
			}

			.searchpassword {
				display: flex;
				align-items: center;
				justify-content: center;

				.searchpassword-item {
					display: flex;
					text-align: right;
					align-items: center;
					margin-top: 20rpx;
					margin-bottom: 20rpx;
					font-size: 24rpx;
					color: $u-color-blue;

					.shu {
						width: 2rpx;
						height: 30rpx;
						background-color: #c8c9cc;
						margin: 0rpx 20rpx;
					}
				}

			}

			.botton {
				margin-top: 20rpx;
			}

			.toggle {
				text-align: center;
				font-size: 28rpx;
				color: $u-color-blue;
				margin-top: 30rpx;
			}
		}

	}
	.tips {
		// display: flex;
		font-size: 24rpx;
		// justify-content: center;
		align-items: center;
		width: 600rpx;
		margin-bottom: 10rpx;
	
		.text {
			color: $u-color-blue;
			display: inline-block;
		}
	}
</style>
